#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

struct passwd_st {
	char *name;
	int uid;
	int gid;
};

void read_pwd_line(struct passwd_st *pwd, char *line)
{
	int i = 0; // 表示读到第几个字段了
	char *last; // 字段开始的位置
	char *next; // 字段结束的位置

	next = last = line;

	// Username : Password : UID : GID : GECOS : Home : Login Shell
	i = 0; // 代表读到了第几个字段
	
	while (last != NULL) {
		// 按':'切分,把last指向下一个':'并把该处字符变成'\0'
		strsep(&next, ":");

		switch (i) {
			case 0: // 第一个字段是用户名
				pwd->name = strdup(last);
				break;
			case 2: // 第三个字段是UID
				pwd->uid = atoi(last);
				break;
			case 3: // 第四个字段是GID
				pwd->gid = atoi(last);
				break;
		}

		last = next;
		i++;
	}
}

int main(void)
{
	FILE *file;
	char *line;
	int c;
	long unsigned int size = 0;
	
	struct passwd_st pwd; // 用于暂存读到的一行用户信息

	file = fopen("/etc/passwd", "r");

	while ((c = getline(&line, &size, file)) != -1)
	{
		// 覆盖掉getline读到的换行符
		line[c - 1] = '\0';

		read_pwd_line(&pwd, line);
		printf("用户名: %30s UID: %8d GID: %8d\n", pwd.name, pwd.uid, pwd.gid);
	}

	return 0;
}

